package codeRandomThoughts.Test134加油站;

public class Solution3 {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            curSum += (gas[i] - cost[i]);
            totalSum += (gas[i] - cost[i]);//记录总的差和,这样只用遍历一次,简化代码

            if (curSum < 0) {
                start = i + 1;//更新起始位置,这里正好for循环的下一个位置就是i+1
                curSum = 0;
            }
        }

        //如果总油量减去总消耗大于等于0,那么一定能跑完一圈
        if (totalSum < 0) return -1;
        return start;
    }
}
